/**
 * File NetworkHelper.java created by Pablo Díaz Fernández
 * on 05/04/2012 for the project supply-chain-simulator
 */
package org.lsk.pfc.scsim.model.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 * Utility to get the IP address or the current server.
 * 
 * @author Pablo Díaz Fernández
 */
public final class NetworkHelper {

	/**
	 * Private constructor to avoid instantiation.
	 */
	private NetworkHelper() {
	}

	/**
	 * Gets the ip address of the computer that runs the class.
	 * 
	 * @return {@link String} whith the IP address.
	 * @throws IOException
	 *             Exception getting the IP.
	 */
	public static String getLocalIP() throws IOException {
		try {
			List<NetworkInterface> ifaces = Collections.list(NetworkInterface
			        .getNetworkInterfaces());
			if (ifaces.size() == 1) {
				InetAddress addr = InetAddress.getLocalHost();
				return addr.getHostAddress();
			}
			if (ifaces.size() > 1) {
				String hostName = InetAddress.getLocalHost().getHostName();
				for (NetworkInterface networkInterface : ifaces) {
					Enumeration<InetAddress> ips = networkInterface
					        .getInetAddresses();
					while (ips.hasMoreElements()) {
						InetAddress ia = ips.nextElement();
						if (ia.getCanonicalHostName().startsWith(hostName)) {
							return ia.getHostAddress();
						}
					}
				}
			}
			throw new IOException("System cannot get IP address for the");
		} catch (IOException e) {
			throw new IOException("System cannot get IP address for the", e);
		}

	}
}
